﻿/*
 * Created by SharpDevelop.
 * User: Admin15
 * Date: 14/08/2014
 * Time: 7:41 PM
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using YoutubeInformationCRUD;

namespace YoutubeInformationGUI
{
	/// <summary>
	/// Description of MainForm.
	/// </summary>
	public partial class MainForm : Form
	{
		private YoutubeChannelRepository channelRepository;
		private YoutubeVideoRepository videoRepository;
		public MainForm()
		{
			//
			// The InitializeComponent() call is required for Windows Forms designer support.
			//
			InitializeComponent();
//			EntityBase.ConnectionString = "Data Source='"+Configuration.Instance.DbPath+"'";
			channelRepository = new YoutubeChannelRepository();
			videoRepository = new YoutubeVideoRepository();
			//
			// TODO: Add constructor code after the InitializeComponent() call.
			//
		}
		
		void MainFormLoad(object sender, EventArgs e)
		{
			cbMode.SelectedIndex = 0;
			ResetGrid();
		}
		
		void BtInsertClick(object sender, EventArgs e)
		{
			try {
				if(tbURL.Text.Trim().Length==0||tbChannelID.Text.Trim().Length==0){
					MessageBox.Show("Some field need to fill data!");
					return;
				}
				YoutubeChannel channel =getChannel();
				var isExist = channelRepository.SelectByChannelId(channel.ChannelId);
				if(isExist==null|| isExist.Count <=0){
					channelRepository.Create(channel);
					MessageBox.Show("Added channel successfully!");
				}else{
					MessageBox.Show("Channel already exist on db,try Update!");
				}
				ResetGrid();
			} catch (Exception ex) {
				MessageBox.Show(ex.Message);
			}
			
		}
		
		void TbURLTextChanged(object sender, EventArgs e)
		{
			try {
				//example https://www.youtube.com/channel/UCfYYi6aJNg70mFYnbBKcMQw
				//==> UCfYYi6aJNg70mFYnbBKcMQw
				var allChar = tbURL.Text.Split(new char[]{'/'});
				tbChannelID.Text = allChar[allChar.Length-1];
			} catch (Exception) {
				//do nothing :D
			}
		}
		
		void BtUpdateClick(object sender, EventArgs e)
		{
			try {
				if(tbURL.Text.Trim().Length==0||tbChannelID.Text.Trim().Length==0){
					MessageBox.Show("Some field need to fill data!");
					return;
				}
				YoutubeChannel channel =getChannel();
				YoutubeChannelRepository repository = new YoutubeChannelRepository();
				var isExist = repository.SelectByChannelId(channel.ChannelId);
				if(isExist==null|| isExist.Count <=0){
					repository.Create(channel);
					MessageBox.Show("Added channel successfully!");
				}else{
					DialogResult result = MessageBox.Show("Do you want to update this channel?", "Confirmation", MessageBoxButtons.YesNoCancel);
					if(result == DialogResult.Yes){
						repository.Update(channel);
						MessageBox.Show("Channel updated successfully!");
					}
				}
				//update video to redownload
				ReDownloadVideo(channel);
				ResetGrid();
			} catch (Exception ex) {
				MessageBox.Show(ex.Message);
			}
		}
		
		void DataGridCellClick(object sender, DataGridViewCellEventArgs e)
		{
			var allChannel = (List<YoutubeChannel>) dataGrid.DataSource;
			var channel = allChannel[e.RowIndex];
			tbChannelID.Text = channel.ChannelId;
			tbDescription.Text = channel.Description;
			tbURL.Text = channel.URL;
			cbMode.SelectedIndex = channel.Mode.HasValue?(channel.Mode.Value-1):1;
		}
		
		public void ResetGrid()
		{
			var allChannel = channelRepository.ToList();
			dataGrid.DataSource = allChannel;
		}
		public YoutubeChannel getChannel()
		{
			YoutubeChannel channel = new YoutubeChannel();
			channel.ChannelId = tbChannelID.Text;
			channel.Description =tbDescription.Text;
			channel.IsActive=true;
			channel.Mode = cbMode.SelectedIndex +1;
			channel.URL = tbURL.Text;
			return channel;
		}
		
		void BtDeleteClick(object sender, EventArgs e)
		{
			DialogResult result = MessageBox.Show("Do you want to delete channel?", "Confirmation", MessageBoxButtons.YesNoCancel);
			if(result == DialogResult.Yes){
				var channel = getChannel();
				//delete all child video
				var allVideoOfChannel = videoRepository.SelectByChannelId(channel.ChannelId);
				videoRepository.Delete(allVideoOfChannel);
				//then
				channelRepository.Delete(channel);
			}
			
			ResetGrid();
		}
		void ReDownloadVideo(YoutubeChannel channel){
			var allVideoOfChannel = videoRepository.SelectByChannelId(channel.ChannelId);
			if(allVideoOfChannel!=null && allVideoOfChannel.Count > 0 ){
				var allVideoToUpdate = allVideoOfChannel.Where(o=>(o.IsActive.HasValue && o.IsActive.Value))
					.Where(o=>(o.Downloaded.HasValue && o.Downloaded.Value))
					.Select(o=> new YoutubeVideo(){
					        	ChannelId = o.ChannelId,
					        	Description = o.Description,
					        	Downloaded = false,
					        	IsActive = true,
					        	Title = o.Title,
					        	Uploader = o.Uploader,
					        	URL = o.URL,
					        	VideoId = o.VideoId
					        }).ToList();
				if(allVideoToUpdate.Count >0){
					videoRepository.Update(allVideoToUpdate);
				}
			}
		}
		
		void DataGridCellDoubleClick(object sender, DataGridViewCellEventArgs e)
		{
			try {
				var allChannel = (List<YoutubeChannel>) dataGrid.DataSource;
				var channel = allChannel[e.RowIndex];
				List<YoutubeVideo> allVideoOfChannel = videoRepository.SelectByChannelId(channel.ChannelId);
				if(allVideoOfChannel==null) allVideoOfChannel = new List<YoutubeVideo>();
				VideoDetails detailForm = new VideoDetails(allVideoOfChannel);
				detailForm.Show();
			} catch (Exception ex) {
				MessageBox.Show(ex.Message);
			}
		}
	}
}
